package xiaocao.learn.java.io.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class BufferToTextExample {
	
	private static final int BSIZE = 1024;
	
	public static void main(String arg[]) throws Exception {
		FileChannel fc = new FileOutputStream("d://test.txt").getChannel();
		fc.write(ByteBuffer.wrap("Some text".getBytes()));
		fc.close();
		fc = new FileInputStream("d://test.txt").getChannel();
		ByteBuffer buff = ByteBuffer.allocate(BSIZE);
		fc.read(buff);
		buff.flip();
		System.out.println(buff.asCharBuffer());
		buff.rewind(); //为重读做准备
		String encoding = System.getProperty("file.encoding");
		System.out.println("Decode using" + encoding + ":" + Charset.forName(encoding).decode(buff));
		fc = new FileOutputStream("d://test.txt").getChannel();
		fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE")));
		fc.close();
		fc = new FileInputStream("d://test.txt").getChannel();
		buff.clear();
		fc.read(buff);
		buff.flip(); //为下一次写做准备
		System.out.println(buff.asCharBuffer());
		
		fc = new FileOutputStream("d://test.txt").getChannel();
		buff = ByteBuffer.allocate(24);
		buff.asCharBuffer().put("Some text");
		fc.write(buff);
		fc.close();
		
		fc = new FileInputStream("d://test.txt").getChannel();
		buff.clear(); // 为下一次读做准备
		fc.read(buff);
		buff.flip();
		System.out.println(buff.asCharBuffer());
		
		
	}

}
